package com.leyou.mall.controller;


import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.R;
import com.leyou.common.utils.AliOss;
import com.leyou.config.AliyunConfig;
import com.leyou.mall.data.dto.MallGoodsCommentDto;
import com.leyou.mall.data.dto.MallGoodsDto;
import com.leyou.mall.data.entity.MallGoods;
import com.leyou.mall.data.entity.MallGoodsPicture;
import com.leyou.mall.data.entity.MallGoodsSpecs;
import com.leyou.mall.data.vo.*;
import com.leyou.mall.mapper.MallGoodsMapper;
import com.leyou.mall.service.MallGoodsPictureService;
import com.leyou.mall.service.MallGoodsService;
import com.leyou.mall.service.MallGoodsSpecsService;
import com.leyou.mall.service.MallSpecsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xhh
 * @since 2022-07-04
 */
//写在类上，不用每个方法都写这个注解了
@RestController
@RequestMapping("/leyou.mall/mall-goods")
public class MallGoodsController {
    @Autowired
    private AliOss aliOss;
    @Autowired
    private OSS ossClient;
    @Autowired
    private MallGoodsMapper mallGoodsMapper;
    @Autowired
    private MallGoodsService mallGoodsSevice;
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private MallGoodsPictureService mallGoodsPictureService;
    @Autowired
    private MallGoodsSpecsService mallGoodsSpecsService;
    @Autowired
    private MallSpecsService mallSpecsService;
    @Autowired
    private MallGoodsCommentController mallGoodsCommentController;

    @PostMapping(value = "/test/oss")
    public String testOss(@RequestBody MultipartFile file){
        System.out.println(file);
        String upload = aliOss.upload(file);
        return upload;
    }
    /**
    * todo 商品列表
    * @param vo
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/5 21:05
    * @deprecated
    */
    @RequestMapping(value = "/goodsList",method = RequestMethod.POST)
    public R goodsList(MallGoodsVo vo){
        System.out.println(vo);
        PageHelper.startPage(vo.getPage(),vo.getLimit());
        List<MallGoodsDto> mallGoodsDtos = mallGoodsMapper.goodsList(vo);
        PageInfo<MallGoodsDto> pageInfo=new PageInfo<MallGoodsDto>(mallGoodsDtos);
        System.out.println(pageInfo.getList());
        for (MallGoodsDto mallGoodsDto : pageInfo.getList()) {
            System.err.println(mallGoodsDto);
            System.err.println(mallGoodsDto.getName());
        }
        return R.ok().data("data",pageInfo);
    }
    /**
    * todo 根据商品id修改上架状态
    * @param goodsId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/6 8:28
    * @deprecated 
    */
    @RequestMapping(value = "/changeState",method = RequestMethod.POST)
    public R changeState(@RequestParam("id")Integer goodsId){
        //System.out.println(goodsId);
        MallGoods mallGoods= new MallGoods();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("id",goodsId);
        MallGoods mallGoods1 = mallGoodsMapper.selectOne(wrapper);
        mallGoods.setId(goodsId);
        mallGoods.setState(!mallGoods1.getState());
        int update = mallGoodsMapper.update(mallGoods, wrapper);
        if(update>0){
            return R.ok();
        }
        else{
            return R.error();
        }
        
    }
    /**
    * todo 批量删除
    * @param goodsIds
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/6 8:43
    * @deprecated
    */
    @RequestMapping(value = "/deletes",method = RequestMethod.POST)
    public R deletes(@RequestParam("ids")Integer[] goodsIds) {
        //for (int i = 0; i < goodsIds.length; i++) {
        //    System.out.println(goodsIds[i]);
        //}
        int i = mallGoodsMapper.deleteBatchIds(Arrays.asList(goodsIds));
        if(i>0){
            return R.ok();
        }else{
            return R.error();
        }
    }
    /**
    * todo 商品图片上传
    * @param file
    * @param id
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/6 14:16
    * @deprecated
    */
    @RequestMapping(value = "/uploadGoodsPic",method = RequestMethod.POST)
    public R uploadGoodsPic(@RequestParam("file") MultipartFile file,@RequestParam("goodsId")Integer id) {
        String fileName = aliOss.upload(file);
        if(!fileName.equals("") && fileName!=null){
            MallGoodsPicture mallGoodsPicture=new MallGoodsPicture();

            //检查是否已经有图片了
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("goods_id",id);
            int count = mallGoodsPictureService.count(queryWrapper);
            //没有图片则设置这个图片为主图片
            if(count==0){
                mallGoodsPicture.setMainPic(true);
            }
            mallGoodsPicture.setGoodsId(id);
            mallGoodsPicture.setUrl(fileName);
            boolean save = mallGoodsPictureService.save(mallGoodsPicture);
            if(save){
                return R.ok();
            }
            else{
                return R.error();
            }
        }
        return R.ok();
    }
    /**
    * todo 删除商品图片
    * @param id
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/6 19:15
    * @deprecated
    */
    @RequestMapping(value = "/deleteGoodsPic",method = RequestMethod.POST)
    public R deleteGoodsPic(@RequestParam("id") Integer id) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", id);
            MallGoodsPicture one = mallGoodsPictureService.getOne(queryWrapper);
            //https://demo-sjh.oss-cn-beijing.aliyuncs.com/images/2022/07/06/16570918491108775.jpg
            String[] split = one.getUrl().split(".com/", 2);
            System.out.println(split[1]);
            //删除操作
            //ossClient.deleteObject(aliyunConfig.getBucketName(), split[1]);
            boolean b = mallGoodsPictureService.removeById(id);
            //如果删除的是主图片再选一个主图片
            if (one.getMainPic()) {
                queryWrapper.clear();
                queryWrapper.eq("goods_id", one.getGoodsId());
                List<MallGoodsPicture> picList = mallGoodsPictureService.list(queryWrapper);
                //当还有图片时选
                if (picList.size() > 0) {
                    for (MallGoodsPicture mallGoodsPicture : picList) {
                        queryWrapper.clear();
                        queryWrapper.eq("id", mallGoodsPicture.getId());
                        mallGoodsPicture.setMainPic(true);
                        //选出第一个为主图片
                        mallGoodsPictureService.update(mallGoodsPicture, queryWrapper);
                        break;
                    }
                }
            }
            one.setMainPic(false);
            queryWrapper.clear();
            queryWrapper.eq("id", id);
            boolean update = mallGoodsPictureService.update(one, queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }
    /**
     * todo 设置商品主图片
     * @param id
     * @return com.leyou.common.pojo.R
     * @author xhh
     * @data 2022/7/6 19:15
     * @deprecated
     */
    @Transactional
    @RequestMapping(value = "/GoodsPicSetMainPic",method = RequestMethod.POST)
    public R GoodsPicSetMainPic(@RequestParam("id") Integer id) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", id);
            //获取当前商品对象
            MallGoodsPicture one = mallGoodsPictureService.getOne(queryWrapper);
            //将主图片改成不是
            queryWrapper.clear();
            queryWrapper.eq("goods_id", one.getGoodsId());
            queryWrapper.eq("main_pic", 1);
            MallGoodsPicture two = mallGoodsPictureService.getOne(queryWrapper);
            two.setMainPic(false);
            boolean update = mallGoodsPictureService.update(two, queryWrapper);
            //将当前商品改成主图片
            one.setMainPic(true);
            queryWrapper.clear();
            queryWrapper.eq("id", id);
            mallGoodsPictureService.update(one,queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }
    /**
    * todo 商品详情的回显
    * @param id
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/6 15:27
    * @deprecated 
    */
    @RequestMapping(value = "/goodsDetail",method = RequestMethod.POST)
    public R goodsDetail(@RequestParam("goodsId")Integer id) {
        GoodsDetailVo vo=new GoodsDetailVo();
        //查询图片
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("goods_id",id);
        wrapper.select("id","main_pic","url");
        List<MallGoodsPicture> picList = mallGoodsPictureService.list(wrapper);
        //商品详情
        MallGoodsDto mallGoodsDto = mallGoodsMapper.goodsOne(id);
        //获取3个评论
        R r = mallGoodsCommentController.phoneShowComment(id, 3);
        List<MallGoodsCommentDto> list=(List<MallGoodsCommentDto>)r.getData().get("list");


        vo.setMallGoodsDto(mallGoodsDto);
        vo.setPicList(picList);
        vo.setCommentDto(list);

        return R.ok().data("data",vo);
    }
    /**
    * todo 商品添加第一步
    * @param vo
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/7 14:19
    * @deprecated 商品分类
    */
    @RequestMapping(value = "/goodsInsertFirstStep",method = RequestMethod.POST)
    public R goodsInsertFirstStep(GoodsInsertVo vo) {

        return R.ok();
    }
    /**
     * todo 商品添加第二步
     * @param mallGoods
     * @return com.leyou.common.pojo.R
     * @author xhh
     * @data 2022/7/7 14:19
     * @deprecated 商品信息
     */
    @RequestMapping(value = "/goodsInsertSecondStep",method = RequestMethod.POST)
    public R goodsInsertSecondStep(MallGoods mallGoods) {
        int insert = mallGoodsMapper.insert(mallGoods);
        return R.ok().data("goodsId",mallGoods.getId());
    }
    /**
     * todo 商品添加第三步
     * @param vo
     * @return com.leyou.common.pojo.R
     * @author xhh
     * @data 2022/7/7 14:19
     * @deprecated 商品规格
     */
    @RequestMapping(value = "/goodsInsertThirdStep",method = RequestMethod.POST)
    public R goodsInsertThirdStep(@RequestBody GenerateInsertSpecsVo vo) {
        boolean saveBatch = mallSpecsService.saveBatch(vo.getList());
        if(saveBatch){
            return R.ok();
        }else{
            return R.error();
        }
    }
    /**
    * todo 根据商品规格 生成返回规格的id
    * @param vo
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/8 14:49
    * @deprecated 
    */
    @RequestMapping(value = "/generateSpecs",method = RequestMethod.POST)
    public R nmb(@RequestBody GenerateSpecsVo vo){
        List<MallGoodsSpecs> mallGoodsSpecsList = vo.getList();
        boolean saveBatch = mallGoodsSpecsService.saveBatch(mallGoodsSpecsList);
        for (MallGoodsSpecs mallGoodsSpecs : mallGoodsSpecsList) {
            System.out.println(mallGoodsSpecs);
        }
        return R.ok().data("list",mallGoodsSpecsList);
    }
    /**
    * todo 手机端首页获取商品列表
    * @param vo
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/13 19:09
    * @deprecated 
    */
    @RequestMapping(value = "/phoneGoodsList",method = RequestMethod.POST)
    public R phoneGoodsList(@RequestBody PhoneGoodsListVo vo){
        Page<MallGoods> page=mallGoodsSevice.page(new Page<>(vo.getPage(),vo.getLimit()));
        QueryWrapper queryWrapper=new QueryWrapper();
        List<PhoneGoodsListVoPut> listVoPuts=new ArrayList<>();
        for (MallGoods record : page.getRecords()) {
            queryWrapper.clear();
            queryWrapper.eq("main_pic",true);
            queryWrapper.eq("goods_id",record.getId());
            PhoneGoodsListVoPut p=new PhoneGoodsListVoPut();
            p.setMallGoods(record);
            p.setPicUrl(mallGoodsPictureService.getOne(queryWrapper).getUrl());
            listVoPuts.add(p);
        }
        return R.ok().data("data",listVoPuts);
    }
    /**
    * todo 手机端商品单查
    * @param goodsId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/13 19:11
    * @deprecated
    */
    @RequestMapping(value = "/phoneGoodsById",method = RequestMethod.POST)
    public R phoneGoodsById(@RequestParam("goodsId") Integer goodsId){
        MallGoods one = mallGoodsSevice.getById(goodsId);
        return R.ok().data("one",one);
    }

}

